# Copyright (C) Maciej Suminski <orson@orson.net.pl>
# Copyright (C) 2020 Seth Hillbrand <seth@kipro-pcb.com>
# Copyright (C) 2023 Andrew Lutsenko <anlutsenko@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, you may find one here:
# https://www.gnu.org/licenses/gpl-3.0.html
# or you may search the http://www.gnu.org website for the version 3 license,
# or you may write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA


import logging

from ..config import BANNED_USERS
from .handler_base import HandlerBase

logger = logging.getLogger(__name__)


class BannedUsersHandler(HandlerBase):
    def handleBannedUserIssue(self, payload: dict):
        if not payload['user']['username'].lower() in BANNED_USERS:
            return False

        project = self.gitlab.projects.get(payload['project']['id'])
        issue_iid = payload['object_attributes']['iid']
        issue = project.issues.get(issue_iid)

        if issue is not None and \
                payload['object_attributes']['action'] == 'open':

            logger.debug("Deleting banned user issue")
            issue.delete()
            return True

        return False

    def handleBannedUserNote(self, payload: dict):
        if not payload['user']['username'].lower() in BANNED_USERS:
            return False

        project = self.gitlab.projects.get(payload['project']['id'])
        note_id = payload['object_attributes']['id']
        note = None

        if "issue" in payload:
            issue = project.issues.get(payload['issue']['iid'])
            note = issue.notes.get(note_id)
        elif "merge_request" in payload:
            mr = project.mergerequests.get(payload['merge_request']['iid'])
            note = mr.notes.get(note_id)
        elif "snippet" in payload:
            snip = project.snippets.get(payload['snippet']['iid'])
            note = snip.notes.get(note_id)
        else:
            return False

        if note is not None:
            logger.debug("Deleting banned user note")
            note.delete()
            return True

        return False

    def handle(self, event: str, payload: dict):
        if event == 'Note Hook':
            return self.handleBannedUserNote(payload)

        if event == 'Issue Hook':
            return self.handleBannedUserIssue(payload)

        return False
